package org.shopen.puremvc.view
{
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	import org.shopen.puremvc.ApplicationConstants;
	import org.shopen.puremvc.view.components.info.ErrorWindow;

	public class ErrorWindowMediator extends Mediator
	{
		public static const NAME : String = "ErrorWindowMediator";
		
		protected var errorWindow : ErrorWindow = null;
		
		public function ErrorWindowMediator(viewComponent:Object=null)
		{
			super(ErrorWindowMediator.NAME, viewComponent);
		}
		
		override public function getMediatorName():String
		{
			return ErrorWindowMediator.NAME;
		}
		
		protected function get application() : ShoPaint
		{
			return viewComponent as ShoPaint;
		}
		
		override public function listNotificationInterests():Array
		{
			return [ApplicationConstants.SHOW_ERROR];
		}
		
		override public function handleNotification(notification:INotification):void
		{
			switch(notification.getName())
			{
				case ApplicationConstants.SHOW_ERROR:
					showError(notification.getBody());
					break;
				default:
					showError();
					break;
			}
		}		
		
		private function showError(error : Object = "") : void
		{
			// Make sure only one error window is shown
			if (errorWindow == null)
			{			
				errorWindow = createWindow(error);
				PopUpManager.addPopUp(errorWindow, application, true);
			}
			else
			{
				errorWindow.errorText += "\n" + error.toString();
			}
			
			PopUpManager.bringToFront(errorWindow);
			PopUpManager.centerPopUp(errorWindow);
		}
		
		private function createWindow(error : Object = "") : ErrorWindow
		{
			var window : ErrorWindow = new ErrorWindow();
			window.title = "Error happened!";
			window.errorText = error.toString();
			
			window.addEventListener(CloseEvent.CLOSE, windowCloseListener);
			
			return window;
		}
		
		private function windowCloseListener(event : CloseEvent) : void
		{
			if (errorWindow == event.target)
			{
				errorWindow.removeEventListener(CloseEvent.CLOSE, windowCloseListener);
				PopUpManager.removePopUp(errorWindow);
				errorWindow = null;
			}
			else
			{
				Alert.show("Some very strange error happened! ErrorWindowMediator.windowCloseListener.");
			}
		}
	}
}